#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/10 11:34
    Desc  :
--------------------------------------
"""
from bson import json_util

from application import mongo
from common.libs.JwtUtils import generate_jwt
from servers.models.projectModel import Project


class User(mongo.Document):
    """
    用户表
    """

    name = mongo.StringField()
    username = mongo.StringField(require = True, unique = True)
    phone = mongo.StringField(require = True, unique_with = 'admin')
    password = mongo.StringField(default = '123456')
    avatar = mongo.StringField()
    is_active = mongo.BooleanField(default = True)
    is_superuser = mongo.BooleanField(default = False)
    admin = mongo.IntField()  # (100 admin, 101 organize)
    projectList = mongo.ListField(mongo.StringField())

    def to_json(self):
        projectList = Project.objects(projectUsername = self.username).all()

        data = {
            '_id': eval(json_util.dumps(self.id)),
            'username': self.username,
            'name': self.name,
            'phone': self.phone,
            'avatar': self.avatar,
            'is_active': self.is_active,
            'is_superuser': self.is_superuser,
            'projectList': projectList,
        }

        return data

    def login_to_json(self):
        """
        登录成功
        :return:
        """
        projectList = []
        for i in self.projectList:
            project = Project.objects(projectName = i)
            if project.count() != 0:
                projectList.append(project.first().to_json())

        token = generate_jwt({'username': self.username, "phone": self.phone, "id": eval(json_util.dumps(self.id)).get('$oid')})

        return {
            '_id': eval(json_util.dumps(self.id)),
            'username': self.username,
            'name': self.name,
            'phone': self.phone,
            'avatar': self.avatar,
            'is_active': self.is_active,
            'is_superuser': self.is_superuser,
            'accesstoken': token,
            'projectList': projectList,
        }
